package com.kyzh.core.pager.login

import android.content.Intent
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import cn.jiguang.verifysdk.api.AuthPageEventListener
import cn.jiguang.verifysdk.api.JVerificationInterface
import cn.jiguang.verifysdk.api.LoginSettings
import com.bytedance.applog.game.GameReportHelper
import com.gushenge.atools.util.ADate
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.getStatusBarHeight
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Code
import com.gushenge.core.dao.GlobalConsts
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.dao.MMKVConsts.sub
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.kyzh.core.R
import com.kyzh.core.utils.*
import com.rxlife.coroutine.RxLifeScope
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.bean.SHARE_MEDIA
import io.github.armcha.autolink.MODE_URL
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.fragment_retrieve_password.*
import rxhttp.wrapper.param.RxHttp
import com.gushenge.core.toast
import com.kyzh.core.activities.*
import rxhttp.toClass


/**
 * Created by Administrator on 2017/8/18 0018.
 */

class LoginActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        initUI()
        initJVerify()
    }

    override fun onBackPressed() {
//        super.onBackPressed()
        if(  linForget.visibility ==View.GONE){
            finish()
        }else{
            val bundle = Bundle()
            bundle.putInt("type",0)
            fragForget.arguments=bundle
            linForget.visibility =View.GONE
            before.visibility = View.VISIBLE
            after.visibility = View.GONE
            fragForget.view?.findViewById<LinearLayout>(R.id.before)?.visibility= View.VISIBLE
            fragForget.view?.findViewById<LinearLayout>(R.id.after)?.visibility= View.GONE
        }
    }

    private fun initJVerify() {
        Log.e("TAG", "initJVerify: ${MMKVConsts.oneKeyLogin}  ${JVerificationInterface.checkVerifyEnable(this)} ")
        if (MMKVConsts.oneKeyLogin){

            if (JVerificationInterface.checkVerifyEnable(this)){
                val settings = LoginSettings()
                settings.isAutoFinish = true //设置登录完成后是否自动关闭授权页
                settings.timeout = 15 * 1000 //设置超时时间，单位毫秒。 合法范围（0，30000],范围以外默认设置为10000
                settings.authPageEventListener = object : AuthPageEventListener() {
                    override fun onEvent(cmd: Int, msg: String) {
                        Log.e("TAG", "onEvent: $cmd  $msg")
                    }
                } //设置授权页事件监听

                val verifyEnable = JVerificationInterface.checkVerifyEnable(this)
                if (!verifyEnable) {
                    Log.d("taf", "当前网络环境不支持认证")
                    return
                }
                JVerificationInterface.setCustomUIWithConfig(oneKeyLoginConfig())
                JVerificationInterface.loginAuth(this, settings) { i, s, s2 ->
                    Log.e("TAG", "initJVerify: $i   $s   $s2", )
                    if (i==6000){
                        onKeyLogin(s)
                    }
                }
            }
        }
    }


    private fun onKeyLogin(token: String) {
        val time = ADate.getStampAs13()
        val sign = md5("${token}${time}riowreopfdwrops21qe")
        RxLifeScope().launch {
            val result = RxHttp.get(GlobalConsts.ONE_KEY_LOGIN)
                .add("token", token)
                .add("t", time)
                .add("sign", sign)
                .add("member_id", sub)
                .toClass<Code<String>>()
                .await()
            if (result.code==1){
                MMKVConsts.uid = result.data?:""
                imLogin()
                LiveEventBus.get<Boolean>("login").post(true)
                finish()
            }else if(result.code == 2){
                setPassword(result.data?:"",0)
            }else{
                result.message.toast()
            }
        }
    }
    var loginbox = false
    private fun initUI() {
        cblogin.isChecked=loginbox
        cblogin.setOnCheckedChangeListener { buttonView, isChecked ->
            loginbox=isChecked
        }
        tvQQLogin.setVisibility(MMKVConsts.qqLogin)
        tvWxLogin.setVisibility(MMKVConsts.wxLogin)
        etAccount.setText(MMKVConsts.username)
        etPassword.setText(MMKVConsts.password)
        AView.setMargins(ivLogo, 0, getStatusBarHeight()+dip(88), 0, 0)
        btLogin.setOnClickListener {
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            val name = etAccount.text.toString().trim()
            val pass = etPassword.text.toString().trim()
            if (name!="" && pass!="") {
                addData(name, pass)
            } else {
                getString(R.string.pleaseSelectHaveEmpty).toast()
            }
        }
        tvPact.addAutoLinkMode(
                MODE_URL
        )
        tvPact.addUrlTransformations(
                GlobalConsts.REGISTER_PACT to "“${getString(R.string.registerAgreement)}”",
                GlobalConsts.PRIVACY_PACT to "“${getString(R.string.privacyPolicy)}”"
        )
        tvPact.urlModeColor = ContextCompat.getColor(this, R.color.colorPrimary)
        tvPact.text = String.format(getString(R.string.loginPrivacy),GlobalConsts.REGISTER_PACT,GlobalConsts.PRIVACY_PACT)
        tvForget.setOnClickListener {
            linForget.visibility = View.VISIBLE
        }

        tvPact.onAutoLinkClick {
            startActivity<BrowserActivity>(GlobalKeys.TITLE to it.transformedText.substring(1, it.transformedText.length - 1), GlobalKeys.LINK to it.originalText)
        }
        tvRegister.setOnClickListener{
            startActivity<RegisterActivity>()
            finish()
        }
        tvPhoneLogin.setOnClickListener{
            startActivity<PhoneLoginActivity>()
            finish()
        }
        ivShowpass.setOnClickListener{
            showPass()
        }
        ivDel.setOnClickListener {
            etAccount.setText("")
            etPassword.setText("")
        }
        tvQQLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.QQ, authListener)
        }
        tvWxLogin.setOnClickListener{
            if(!loginbox){
                getString(R.string.pleasecheck).toast()
                return@setOnClickListener
            }
            UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener)
        }
    }
    /*tvFindPassword -> startActivity<BaseFragmentActivity>(GlobalKeys.TYPE to BaseFragmentActivity.RETRIEVE_PASSWORD)*/


    private fun showPass() {
        if (etPassword.transformationMethod != HideReturnsTransformationMethod.getInstance()) {
            etPassword.transformationMethod = HideReturnsTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_login_showpassword))
        } else {
            etPassword.transformationMethod = PasswordTransformationMethod.getInstance()
            ivShowpass.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_login_hidepassword))
        }
    }

    private fun addData(userName: String, password: String) {
        UserImpl.login(userName, password, object : ResultListener {
            override fun success() {
                MMKVConsts.username = userName
                MMKVConsts.password = password
                imLogin()
                LiveEventBus.get<Boolean>("login").post(true)
                finish()
            }

            override fun error(error: String) {
                error.toast()
            }
        })
    }
    //Im登录
    private fun imLogin(){
//        if(MMKVConsts.imOpen){
//            LiveRequest.geiLiveUserUid{
//                this?.apply {
//                    TUILogin.login(live_uid,live_sign,object :V2TIMCallback{
//                        override fun onSuccess() {
//                            Log.e(TUIUtils.TAG, "登录成功 onSuccess" )
//                        }
//
//                        override fun onError(p0: Int, p1: String?) {
//                            Log.e(TUIUtils.TAG, "onError: $p0  $p1")
//                        }
//                    })
//                }
//            }
//        }
    }
    // 设置密码  type ==1  QQ   2 wx
    fun setPassword(token: String? ,type :Int){
        PasswordActivity.start(this, token, type)
    }
    var authListener: UMAuthListener = object : UMAuthListener {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        override fun onStart(platform: SHARE_MEDIA) {
        }
        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        override fun onComplete(platform: SHARE_MEDIA, action: Int, data: Map<String, String>) {
            Log.e("12312312", data.toString())
            if (platform == SHARE_MEDIA.QQ) {
                UserImpl.checkReg(data["accessToken"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["accessToken"] ?: "", "1",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        GameReportHelper.onEventRegister("QQ",true);
                        setPassword(data["accessToken"] ?: "",1)
                    }
                }
            } else {
                UserImpl.checkReg(data["uid"].toString() ){
                    val code1 = this
                    if(code1.code == 1){
                        UserImpl.loginByQqWx(data["uid"] ?: "", "2",null,null) {
                            if(code == 1){
                                MMKVConsts.uid= this.data.toString()
                                imLogin()
                                LiveEventBus.get<Boolean>("login").post(true)
                                finish()
                            }else{
                                message.toast()
                            }
                        }
                    }else{
                        GameReportHelper.onEventRegister("wx",true);
                        setPassword(data["uid"] ?: "",2)
                    }
                }
            }
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        override fun onError(platform: SHARE_MEDIA, action: Int, t: Throwable) {
            Log.e("TAG", "onError: "+t.localizedMessage +"---" +action)
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        override fun onCancel(platform: SHARE_MEDIA, action: Int) {
            getString(R.string.cancelLogin).toast()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 1000){
            if(resultCode == RESULT_OK){
                finish()
            }
        }else{

            UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
        }

    }

}
